package com.kun.portal.webframe.util.eventQuene;

import com.lmax.disruptor.EventFactory;
import com.lmax.disruptor.RingBuffer;
import com.lmax.disruptor.SleepingWaitStrategy;
import com.lmax.disruptor.WaitStrategy;
import com.lmax.disruptor.dsl.BasicExecutor;
import com.lmax.disruptor.dsl.Disruptor;
import com.lmax.disruptor.dsl.ProducerType;

import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

public class EventProcessor {

     private static String block = "";
     private static  MessageEventProducerWithTranslator producer;
     private static  void init(){
        Executor executor = Executors.newCachedThreadPool();

        // Specify the size of the ring buffer, must be power of 2.
        int bufferSize = 1024;

        // Construct the Disruptor
        EventFactory<MessageEvent> eventFactory = new MessageEventFactory();

        Disruptor<MessageEvent> disruptor = new Disruptor<MessageEvent>(eventFactory, bufferSize, executor, ProducerType.SINGLE,  new SleepingWaitStrategy());

        // Connect the handler
        disruptor.handleEventsWith(new MessageEventHandler());

        // Start the Disruptor, starts all threads running
        disruptor.start();

        // Get the ring buffer from the Disruptor to be used for publishing.
        RingBuffer<MessageEvent> ringBuffer = disruptor.getRingBuffer();

        // Start the Disruptor, starts all threads running

        producer = new MessageEventProducerWithTranslator(ringBuffer);

    }

     public static void publish(Message message){
          if(producer==null){
              synchronized (block){
                  if(producer==null){
                      init();
                  }
              }
          }
          producer.onData(message);
     }
}
